<template>
  <div class="saveUpdate">
    <el-dialog
      :title="id?'收款资源配置编辑':'收款资源配置新增'"
      :visible.sync="showDialog"
      @close="$emit('update:showUpdate', false)"
      :showUpdate="showUpdate"
      width="700px"
    >
      <el-form :model="DetailInfo" ref="saveChn"  label-width="140px" size="mini" :rules="rules">
        <dialog-wrapper :MaxWidth="600">
          <el-row>
            <!-- <el-col :span="12">
              <el-cascader :options="options" v-model="selectedOptions" @change="handleChange"></el-cascader>
            </el-col>-->

            <el-col :span="12">
              <el-form-item prop="receipt_type" label="收款方式">
                <el-select v-model="DetailInfo.receipt_type" clearable placeholder="请选择" :disabled="!!id">
                  <el-option
                    v-for="item in RecepiptType"
                    :key="item.id"
                    :label="item.name"
                    :value="parseInt(item.id)"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="receipt_method" label="账号类型">
                <el-select v-model="DetailInfo.receipt_method" clearable placeholder="请选择" :disabled="!!id">
                  <el-option
                    v-for="item in getRecepiptMethodType()"
                    :key="item.id"
                    :label="item.name"
                    :value="parseInt(item.id)"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="16">
              <el-form-item
                prop="account"
                v-if="DetailInfo.receipt_method&&[1,3].includes(DetailInfo.receipt_method)"
                :label="RecepiptType.find((n)=>n.id===DetailInfo.receipt_type).children.find((n)=>n.id===DetailInfo.receipt_method).accountName"
              >
                <el-input v-model="DetailInfo.account" placeholder="..." :disabled="!!id"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="16">
              <el-form-item
                prop="mch_name"
                v-if="DetailInfo.receipt_method&&[2,4].includes(DetailInfo.receipt_method)"
                label="商家名称"
              >
                <el-input v-model="DetailInfo.mch_name" placeholder="..." :disabled="!!id"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="16">
              <el-form-item
                prop="nickname"
                v-if="DetailInfo.receipt_method&&[3].includes(DetailInfo.receipt_method)"
                label="微信昵称"
              >
                <el-input v-model="DetailInfo.nickname" placeholder="..." :disabled="!!id"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="DetailInfo.receipt_method&&[1,5].includes(DetailInfo.receipt_method)">
            <el-col :span="12">
              <el-form-item prop="first_name" :label="`${receiptTypeString}姓：`">
                <el-input v-model="DetailInfo.first_name" placeholder="..." :disabled="!!id"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="last_name" :label="`${receiptTypeString}名：`">
                <el-input v-model="DetailInfo.last_name" placeholder="..." :disabled="!!id"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="DetailInfo.receipt_method&&[5].includes(DetailInfo.receipt_method)">
            <el-col :span="16">
              <el-form-item prop="account" label="银行卡号：">
                <el-input v-model="DetailInfo.account" placeholder="..." :disabled="!!id"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="DetailInfo.receipt_method&&[5].includes(DetailInfo.receipt_method)">
            <el-col :span="16">
              <el-form-item prop="bank_code" label="开户银行：">
                  <el-select v-model="DetailInfo.bank_code" clearable placeholder="请选择" :disabled="!!id">
                    <el-option
                      v-for="(type, index) of BankCode"
                      :key="index"
                      :label="type"
                      :value="index"
                    ></el-option>
                  </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row v-if="DetailInfo.receipt_method&&[5].includes(DetailInfo.receipt_method)">
            <el-col :span="16">
              <el-form-item prop="bank_branch" label="开户支行：">
                <el-input v-model="DetailInfo.bank_branch" placeholder="..." :disabled="!!id"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- <el-row>
            <el-col :span="24">
              <el-form-item prop="nick_name" label="微信昵称：">
                <el-input v-model="DetailInfo.nick_name" placeholder="..."></el-input>
              </el-form-item>
            </el-col>
          </el-row> -->
          <el-row v-if="DetailInfo.receipt_method&&[1].includes(DetailInfo.receipt_method)">
            <el-col :span="16">
              <el-form-item prop="ali_zkl" label="吱口令：">
                <el-input
                  type="textarea"
                  rows="2"
                  v-model="DetailInfo.ali_zkl"
                  placeholder="..."
                  :disabled="!!id"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12" v-if="DetailInfo.receipt_method&&[1].includes(DetailInfo.receipt_method)">
              <el-form-item label="账号二维码：">
                <!--<el-input v-model="DetailInfo.qr_code" placeholder="..."></el-input>-->
                <el-upload
                  :disabled="!!id"
                  ref="uploadQr"
                  class="avatar-uploader"
                  :auto-upload="false"
                  action
                  list-type="picture-card"
                  :show-file-list="false"
                  :multiple="false"
                  :on-change="handlePictureCardPreviewAccount"
                >
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                 <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
                <!-- <span style="color: #169ed7">*收款二维码请勿设置收款金额</span> -->
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="DetailInfo.receipt_method&&[1,2,3,4].includes(DetailInfo.receipt_method)">
              <el-form-item :prop="[1].includes(DetailInfo.receipt_method)?'qr_codeno':'qr_code'" :label="DetailInfo.receipt_method&&[1,3].includes(DetailInfo.receipt_method)?'个人收款码：':'商家收款码：'">
                <!--<el-input v-model="DetailInfo.qr_code" placeholder="..."></el-input>-->
                <el-upload
                  :disabled="!!id"
                  ref="uploadQr"
                  class="avatar-uploader"
                  :auto-upload="false"
                  action
                  list-type="picture-card"
                  :show-file-list="false"
                  :multiple="false"
                  :on-change="handlePictureCardPreview"
                >
                <img v-if="accountimageUrl" :src="accountimageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
                <!-- <span style="color: #169ed7">*收款二维码请勿设置收款金额</span> -->
              </el-form-item>
            </el-col>
          </el-row>

          <el-divider></el-divider>

          <el-row>
              <el-col :span="4" v-if="DetailInfo.receipt_method&&[2].includes(DetailInfo.receipt_method)">
                  <el-row>
                      <el-col :span="6">
                          <el-form-item label-width="0px">
                              <el-checkbox :disabled="!!id" v-model="DetailInfo.can_huabei">支持花呗</el-checkbox>
                          </el-form-item>
                      </el-col>
                      <!-- <el-col :span="14">
                          <el-form-item label="费率" label-width="60px">
                              <el-input class="numberInput" type="number" v-model.number="DetailInfo.huabei_fee_rate" size="mini"></el-input>
                          </el-form-item>
                      </el-col>
                      <el-col :span="4">
                          <el-form-item label-width="0px">%</el-form-item>
                      </el-col> -->
                  </el-row>
              </el-col>
              <el-col :span="4" v-if="DetailInfo.receipt_method&&[2,4].includes(DetailInfo.receipt_method)">
                  <el-row>
                      <el-col :span="7">
                          <el-form-item label-width="0px">
                              <el-checkbox :disabled="!!id" v-model="DetailInfo.can_credit">支持信用卡</el-checkbox>
                          </el-form-item>
                      </el-col>
                      <!-- <el-col :span="14">
                          <el-form-item label="费率" label-width="60px">
                              <el-input type="number" v-model.number="DetailInfo.credit_fee_rate" size="mini"></el-input>
                          </el-form-item>
                      </el-col>
                      <el-col :span="3">
                          <el-form-item label-width="0px">%</el-form-item>
                      </el-col> -->
                  </el-row>
              </el-col>
          </el-row>
          <el-row>
              <el-col :span="24" hidden v-if="DetailInfo.receipt_method&&[2,4].includes(DetailInfo.receipt_method)">
                  <el-row>
                      <el-col :span="4">
                          <el-form-item label-width="0px">
                              <el-checkbox v-model="DetailInfo.can_person" :disabled="!!id">
                                  {{[2].includes(DetailInfo.receipt_method)?'支持支付宝':'支持微信'}}
                              </el-checkbox>
                          </el-form-item>
                      </el-col>
                  </el-row>
              </el-col>
          </el-row>

          <el-divider v-if="DetailInfo.receipt_method&&[2,4].includes(DetailInfo.receipt_method)"></el-divider>


          <el-row>
                <el-col :span="12">
                  <el-form-item prop="min_user_level" label="展示条件：">
                      <el-select v-model="DetailInfo.min_user_level"  placeholder="请选择" :disabled="!!id">
                          <el-option v-for="item in user_level" :key="item.value" :label="item.label" :value="parseInt(item.value)"></el-option>
                      </el-select>
                      <!-- <el-input type="number" v-model.number="DetailInfo.min_user_level"></el-input> -->
                  </el-form-item>
              </el-col>
                <el-col :span="12">
                  <el-form-item label="每日收款上限：" >
                      <el-input :disabled="!!id" placeholder="不填则不限" type="number" v-model.number="DetailInfo.daily_amount_limit" size="mini"></el-input>
                  </el-form-item>
              </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="账号状态：">
                <el-switch v-model="DetailInfo.status" :disabled="!!id"></el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="自助充值：">
                <el-switch v-model="DetailInfo.auto_arrival"></el-switch>
              </el-form-item>
            </el-col>
          </el-row>
           <el-row v-if="DetailInfo.receipt_method&&[5].includes(DetailInfo.receipt_method)&&DetailInfo.auto_arrival">
              <el-col :span="12">
                  <el-form-item prop="phone" label="绑定手机号">
                      <el-input v-model="DetailInfo.phone"></el-input>
                  </el-form-item>
              </el-col>
            </el-row>
        </dialog-wrapper>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="$emit('update:showUpdate', false)" size="small">取 消</el-button>
         <el-button v-if="id" type="primary" :loading="loading" @click="updateDetail" size="small">确 定
                </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import DialogWrapper from '@/components/DialogWrapper'
import {
  getAgencyReceiptDetail,
  getQiniuUploadToken,
  qiniuUpload,
  updateAgencyReceipt
} from '@/api'
import { useVcode } from "../../utils/CommonJs";
export default {
  components: { DialogWrapper},
  computed:{
      receiptTypeString(){
          const type = this.DetailInfo.receipt_type;
          for(let i=0;this.RecepiptType.length;i++){
              const item = this.RecepiptType[i];
              if(item.id == type){
                  return item.name;
              }
          }
          return ''
      }
  },
  data() {
    let validatemin = (rule, value, callback) => {
      if (value < 0) {
        callback(new Error('不能为负数'))
      } else {
        callback()
      }
    }
    // let validatemax = (rule, value, callback) => {
    //   if (value < this.DetailInfo.min_accumulated_recharge) {
    //     callback(new Error('最大金额不能最小金额'))
    //   } else {
    //     callback()
    //   }
    // }

    return {
      user_level:[
          {
              label:'免费用户',
              value:0
          },
          {
              label:'普通用户',
              value:1
          },
          {
              label:'中级用户',
              value:2
          },
          {
              label:'高级用户',
              value:3
          },
      ],
      setbank: false,
      showDialog: this.showUpdate,
      loading: false,
      DetailInfo: {
        status: false,
        auto_arrival: false,
        min_user_level:0,
      },
      quotaList: [],
      RecepiptType: this.$store.state.app.RecepiptType,
      BankCode: this.$store.state.app.BankCode,
      rules: {
        min_user_level: [
          { validator: validatemin, trigger: 'blur' },
          { type: 'number', message: '必须为数字值' },
        ],
        // min_accumulated_recharge: [
        //   { validator: validatemin, trigger: 'blur' },
        //   { type: 'number', message: '必须为数字值' },
        // ],
        // max_accumulated_recharge: [
        //   { validator: validatemax, trigger: 'blur' },
        //   { type: 'number', message: '必须为数字值' },
        // ],
        account: [{ required: true, message: '不能为空', trigger: 'blur' }],
        first_name: [{ required: true, message: '不能为空', trigger: 'blur' }],
        last_name: [{ required: true, message: '不能为空', trigger: 'blur' }],
        phone: [{ required: true, message: '不能为空', trigger: 'blur' }],
        qr_code: [{ required: true, message: '不能为空', trigger: 'blur' }],
        bank_code: [{ required: true, message: '不能为空', trigger: 'blur' }],
        bank_branch: [{ required: true, message: '不能为空', trigger: 'blur' }],
        receipt_type:[{ required: true, message: '不能为空', trigger: 'blur' }],
        receipt_method:[{ required: true, message: '不能为空', trigger: 'blur' }],
        mch_name:[{ required: true, message: '不能为空', trigger: 'blur' }],
        nickname:[{ required: true, message: '不能为空', trigger: 'blur' }],
      },
      dialogVisible: false,
      options: [
        {
          value: 1,
          label: '支付宝',
          children: [{ value: 1, label: '支付宝账号' }]
        },
        { value: 2, label: '微信' },
        { value: 3, label: '银行卡' },
        { value: 4, label: '花呗' },
        { value: 5, label: '信用卡' }
      ],
      selectedOptions: [],
      imageUrl:'',
      accountimageUrl:''
    }
  },
  props: {
    showUpdate: {
      type: Boolean,
      default: false
    },
    id: {
      type: Number
    },
    settleCycle: {
      type: Object
    }
  },
  created() {
    if (this.id) {
      this.getDetail()
    }
  },
  methods: {
    handlePictureCardPreview(f) {
      this.fileHandle(f,'qr_code')
      this.accountimageUrl=URL.createObjectURL(f.raw);
    },
    handlePictureCardPreviewAccount(f)
    {
      this.fileHandle(f,'account_qr_code')
      this.imageUrl = URL.createObjectURL(f.raw);
    },
    fileHandle(f,qrtype)
    {
      getQiniuUploadToken().then(res => {
        if (res.status === 0) {
          let data = new FormData()
          //创建新文件对象（实现更名）
          var fileName =
            new Date().getTime() + f.name.substring(f.name.lastIndexOf('.'))
          data.append('file', f.raw)
          data.append('key', fileName)
          data.append('token', res.data.token)
          qiniuUpload(data).then(res => {
            console.log(res.key)
            this.$set(this.DetailInfo, qrtype, res.key)
            // this.DetailInfo.qr_code = res.key
          })
        }
      })
    },

    getDetail() {
      getAgencyReceiptDetail(this.id).then(res => {
        if (res.status === 0) {
            if (res.data.daily_amount_limit) {
                res.data.daily_amount_limit = Number(res.data.daily_amount_limit) / 100
            }
            this.DetailInfo = res.data
            this.accountimageUrl = res.data.qr_code ? this.$store.state.app.qiniuUrl + res.data.qr_code : ''
            this.imageUrl = res.data.account_qr_code ? this.$store.state.app.qiniuUrl + res.data.account_qr_code : ''
        }
      })
    },
    getRecepiptMethodType(){
      if(!this.DetailInfo.receipt_type)
      {
        return []
      }
      return this.RecepiptType.find((n)=>n.id===this.DetailInfo.receipt_type).children
    },
    handleClose(tag) {
      let self = this
      self
        .$confirm('您确认删除档位&quot;' + tag.amount + '&quot;?', '温馨提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          dangerouslyUseHTMLString: true,
          //   type: 'warning',
          center: true
        })
        .then(() => {
          self.quotaList.splice(self.quotaList.indexOf(tag), 1)
        })
    },
    handleChange(value) {
      console.log(value)
      console.log('tag', JSON.stringify(this.selectedOptions))
    },
    validRequire() {
        if (this.DetailInfo.receipt_method === 2) {
            if (!this.DetailInfo.can_huabei && !this.DetailInfo.can_credit && !this.DetailInfo.can_person) {
                return false
            } else {
                return true
            }
        } else if (this.DetailInfo.receipt_method === 4) {
            if (!this.DetailInfo.can_credit && !this.DetailInfo.can_person) {
                return false
            } else {
                return true
            }
        } else {
            return true
        }
    },
    updateDetail(){
        let queryStr = Object.assign({}, this.DetailInfo, {})
        if (this.DetailInfo.daily_amount_limit) {
            Object.assign(queryStr, { daily_amount_limit: this.DetailInfo.daily_amount_limit * 100, })
        }

        useVcode(this, () => {
            if (!this.validRequire()) {
                this.$message.error('请至少勾选一种支付方式！')
                return
            }
            this.$confirm('保存后账号信息无法更改，可修改其它账号设置,是否确认保存？', '确认信息', {
                    distinguishCancelAndClose: true,
                    confirmButtonText: '保存',
                    cancelButtonText: '放弃'
                })
                .then(() => {
                    this.$refs.saveChn.validate(valid => {
                        if (valid) {
                            updateAgencyReceipt(queryStr, this.id).then(res => {
                                if (res.status === 0) {
                                    this.$message({ message: '编辑成功。', type: 'success' })
                                    this.$emit('update:showUpdate', false)
                                }
                            })
                        }
                    })
                })
        })
    }
    
  },
  watch: {
    showUpdate() {
      this.showDialog = this.showUpdate
    },
    'DetailInfo.receipt_type'(val, oldVal){
      if(val!=oldVal)
      {
        if(!this.id)
        {
          this.DetailInfo= {status: false,auto_arrival: false,receipt_type:val}
          // this.$set(this.DetailInfo,'receipt_method',null)
        }

      }
    },

  }
}
</script>

<style scoped lang="postcss">
.el-tag .el-icon-close {
  top: -15px;
  right: -15px;
  border: 1px solid;
  background: #b4b3b3;
}


  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    line-height: 148px;
    text-align: center;
  }
  .avatar {
    width: 148px;
    height: 148px;
    display: block;
  }
</style>

